import JDBC.jdbc_user;
import jie_yue.look;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.time.LocalDateTime;

import static javax.swing.UIManager.getInt;

public class Swing1 extends JFrame {

    public void GUI(int i) throws SQLException {
        int id = i;
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime dateTime1 = dateTime.plusDays(7);

        setTitle("学生个人界面");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(800, 600);
        setLocation(500,200);
        setLayout(new BorderLayout());

        //创建按钮与输入框
        JPanel inputPanel = new JPanel(new GridLayout(2,4,30,10));
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 四周留白10px

        JButton informationButton = new JButton("借阅信息");
        inputPanel.add(informationButton);
        JButton borrowingButton = new JButton("借阅");
        inputPanel.add(borrowingButton);
        JButton returnButton = new JButton("归还");
        inputPanel.add(returnButton);
        JButton suanButton= new JButton("刷新");
        inputPanel.add(suanButton);

        JButton createButton = new JButton("查询");
        inputPanel.add(createButton);

        JLabel label_1 = new JLabel("图书编号：");
        inputPanel.add(label_1);
        JTextField idInput = new JTextField(10);
        inputPanel.add(idInput);

        add(inputPanel, BorderLayout.NORTH);

        //创建表格
        String[] columns = {"图书编号", "名称", "作者","出版社","数量","分类","登记日期"};
        DefaultTableModel tableModel = new DefaultTableModel(columns, 0);
        JTable JTable = new JTable(tableModel);
        JScrollPane jScrollPane = new JScrollPane(JTable);
        add(jScrollPane, BorderLayout.CENTER);

        informationButton.addActionListener(e-> new look(id));
        borrowingButton.addActionListener(e-> borrowing(id,idInput.getText(),dateTime,dateTime1));
        returnButton.addActionListener(e-> return_book(id,idInput.getText(),dateTime,dateTime1));
        suanButton.addActionListener(e-> shuaxin(tableModel));
        createButton.addActionListener(e-> create(tableModel, idInput.getText()));

        loadDate(tableModel);
        setVisible(true);
    }

    //刷新
    private void shuaxin(DefaultTableModel tableModel) {
        tableModel.setRowCount(0);
        loadDate(tableModel);
    }

    //显示
    private void loadDate(DefaultTableModel tableModel) {
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select * from BOOK  ORDER BY BOOK_ID ASC");
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {
                Object[] row = {
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5),
                        rs.getString(6),
                        rs.getDate(7)
                };
                tableModel.addRow(row);
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败："+e.getMessage());
        }
    }

    //查询
    private void create(DefaultTableModel tableModel, String text) {
        tableModel.setRowCount(0);
        try{
            int i= Integer.parseInt(text);
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select * from BOOK where BOOK_ID=?");
            pstm.setInt(1,i);//写入
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {
                Object[] row = {
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5),
                        rs.getString(6),
                        rs.getDate(7)
                };
                tableModel.addRow(row);
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("查询失败："+e.getMessage());
        }
    }

    //借阅
    private void borrowing(int id, String label_1, LocalDateTime dateTime, LocalDateTime dateTime1) {
        int book_id = Integer.parseInt(label_1);
        String booknum=null;
        Integer stu_id=id;
        Timestamp timestamp = Timestamp.valueOf(dateTime);
        Timestamp timestamp1 = Timestamp.valueOf(dateTime1);
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select BOOK_NUM from BOOK where BOOK_ID=?");
            pstm.setInt(1,book_id);
            ResultSet rs = pstm.executeQuery();
            if (rs.next()) { // 先检查是否有结果
                booknum= rs.getString("BOOK_NUM");
            } else {
                showError("未找到ID为 " + book_id + " 的书籍记录");
                return; // 无结果时提前返回
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败1："+e.getMessage());
        }

        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select BOOK_ID from BORROW where STU_ID=?");
            pstm.setInt(1,stu_id);
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {
                int str[] = {
                        rs.getInt(1)
                };
                if(str[0]==book_id){
                    JOptionPane.showMessageDialog(null, "您已借阅过此书！");
                    return;
                }
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败2："+e.getMessage());
        }

        int a= Integer.parseInt(booknum);

        if(a==0){
            JOptionPane.showMessageDialog(null, "书籍储量不足！");
        }
        else{
            try{
                Integer b=a-1;
                Connection conn = jdbc_user.getConnection();
                PreparedStatement pstm = conn.prepareStatement("update BOOK set BOOK_NUM=? where BOOK_ID=?");
                pstm.setInt(1,b);
                pstm.setInt(2,book_id);
                ResultSet rs = pstm.executeQuery();
                pstm.close();
                conn.close();
            } catch (SQLException e){
                showError("加载失败3："+e.getMessage());
            }
            try{
                Connection conn = jdbc_user.getConnection();
                PreparedStatement pstm = conn.prepareStatement("insert into BORROW(STU_ID,BOOK_ID,BORROW_DATE,EXPECT_RETURN_DATE) values(?,?,?,?)");
                pstm.setInt(1,stu_id);
                pstm.setInt(2,book_id);
                pstm.setTimestamp(3, timestamp);
                pstm.setTimestamp(4, timestamp1);
                ResultSet rs = pstm.executeQuery();
                pstm.close();
                conn.close();
            } catch (SQLException e){
                showError("加载失败4："+e.getMessage());
            }
            JOptionPane.showMessageDialog(null, "借阅成功！");
        }
    }

    //归还
    private void return_book(int id, String text, LocalDateTime dateTime, LocalDateTime dateTime1) {
        int book_id = Integer.parseInt(text);
        int stu_id=id;
        Timestamp timestamp = Timestamp.valueOf(dateTime);
        Timestamp timestamp1 = Timestamp.valueOf(dateTime1);
        String booknum=null;
        LocalDateTime borrowDate = null;
        //查看是否借阅有这本书
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select BOOK_ID from BORROW where STU_ID=?");
            pstm.setInt(1,stu_id);
            ResultSet rs = pstm.executeQuery();
            int a=0;
            while (rs.next()) {
                int str[] = {
                        rs.getInt(1)
                };
                if(str[0]==book_id){
                    a=1;
                }
            }
            if(a==0){
                JOptionPane.showMessageDialog(null, "您未借阅此书！");
                return;
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败1："+e.getMessage());
        }
        //获取借书时间
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select BORROW_DATE from BORROW where STU_ID=? and BOOK_ID=?");
            pstm.setInt(1,stu_id);
            pstm.setInt(2,book_id);
            ResultSet rs = pstm.executeQuery();
            if (rs.next()) {
                Timestamp timestamp3 = rs.getTimestamp("BORROW_DATE");
                borrowDate = timestamp.toLocalDateTime();
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败2："+e.getMessage());
        }
        //删除借阅记录
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("delete from BORROW where STU_ID=? and BOOK_ID=?");
            pstm.setInt(1,stu_id);
            pstm.setInt(2,book_id);
            ResultSet rs = pstm.executeQuery();
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败3："+e.getMessage());
        }
        //获取图书数量
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select BOOK_NUM from BOOK where BOOK_ID=?");
            pstm.setInt(1,book_id);
            ResultSet rs = pstm.executeQuery();
            if (rs.next()) { // 先检查是否有结果
                booknum= rs.getString("BOOK_NUM");
            } else {
                showError("未找到ID为 " + book_id + " 的书籍记录");
                return; // 无结果时提前返回
            }
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败4："+e.getMessage());
        }
        //归还图书，数量+1
        try{
            Integer b= Integer.parseInt(booknum)+1;
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("update BOOK set BOOK_NUM=? where BOOK_ID=?");
            pstm.setInt(1,b);
            pstm.setInt(2,book_id);
            ResultSet rs = pstm.executeQuery();
            pstm.close();
            conn.close();
        } catch (SQLException e){
            showError("加载失败5："+e.getMessage());
        }
        //写入还书记录表
        try{
            Connection conn = jdbc_user.getConnection();
            PreparedStatement pstm = conn.prepareStatement("insert into RETURN_TABLE(STU_ID,BOOK_ID,BORROW_DATE,RETURN_DATE) values(?,?,?,?)");
            pstm.setInt(1,stu_id);
            pstm.setInt(2,book_id);
            pstm.setTimestamp(3, Timestamp.valueOf(borrowDate));
            pstm.setTimestamp(4, timestamp);
            ResultSet rs = pstm.executeQuery();
            pstm.close();
            conn.close();
            JOptionPane.showMessageDialog(null, "还书成功！");
        } catch (SQLException e){
            showError("加载失败6："+e.getMessage());
        }
    }

    //弹窗
    private void showError(String s) {
        JOptionPane.showMessageDialog(this,s,"错误",JOptionPane.ERROR_MESSAGE);
    }
}
